package com.niiwoo.civet.account.service.local.trade;

import com.niiwoo.civet.account.dao.entity.OrderSuccessAccounting;
import com.niiwoo.civet.account.dao.entity.OrderSuccessAccountingExample;
import com.niiwoo.civet.account.dao.mapper.OrderSuccessAccountingMapper;
import com.niiwoo.civet.account.enums.OrderTypeEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 交易成功幂等记账服务类
 * Created by wangjichao on 2018/4/24.
 */
@Service
@Slf4j
public class OrderSuccessAccountingLocalService {

    @Autowired
    private OrderSuccessAccountingMapper orderSuccessAccountingMapper;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;


    /**
     * 新增交易成功幂等记账记录
     * @param orderId
     * @param orderType
     * @return
     */
    @Transactional
    public Long insertOrderSuccessAccounting(Long orderId, OrderTypeEnum orderType){
        //插入幂等记账表
        OrderSuccessAccounting orderSuccessAccounting = new OrderSuccessAccounting();
        orderSuccessAccounting.setId(snowflakeIdWorker.nextId());
        orderSuccessAccounting.setOrderId(orderId);
        orderSuccessAccounting.setOrderType(orderType.getCode());
        Date now = new Date();
        orderSuccessAccounting.setCreateTime(now);
        orderSuccessAccounting.setUpdateTime(now);
        orderSuccessAccountingMapper.insertSelective(orderSuccessAccounting);

        return orderSuccessAccounting.getId();
    }

    /**
     * 根据订单ID和订单类型查询记账记录
     * @param orderId
     * @param orderType
     * @return
     */
    @Transactional
    public OrderSuccessAccounting queryOrderSuccessAccountingByOrderIdAndOrderType(Long orderId,OrderTypeEnum orderType){
        OrderSuccessAccountingExample example = new OrderSuccessAccountingExample();
        OrderSuccessAccountingExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andOrderTypeEqualTo(orderType.getCode());
        List<OrderSuccessAccounting> orderSuccessAccountingList = orderSuccessAccountingMapper.selectByExample(example);
        if(orderSuccessAccountingList == null || orderSuccessAccountingList.isEmpty()){
            return null;
        }
        return orderSuccessAccountingList.get(0);
    }

}
